<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <my-header @AddTodo="AddTodo"></my-header>
        <my-list :TodoList="TodoList"></my-list>
        <my-footer
          :TodoList="TodoList"
          :ClearTodos="ClearTodos"
          @TotalChecked="TotalChecked"
        ></my-footer>
      </div>
    </div>
  </div>
</template>

<script>
import MyList from "./components/MyList.vue";
import MyHeader from "./components/MyHeader.vue";
import MyFooter from "./components/MyFooter.vue";
export default {
  name: "App",
  components: { MyHeader, MyList, MyFooter },
  data() {
    //ooo
    return {
      // 获取本地存储的todos，若localStorage.getItem('todos')为null则为空数组
      TodoList: JSON.parse(localStorage.getItem('todos')) || [],
    };
  },
  methods: {
    // 勾选
    handleChange(id) {
      this.TodoList.forEach((element) => {
        if (element.id === id) {
          element.done = !element.done;
        }
      });
    },
    // 增
    AddTodo(todoObj) {
      // console.log(todoObj)
      this.TodoList.unshift(todoObj);
    },
    // 删
    DeleteTodo(todo) {
      // console.log(todo);
      this.TodoList.shift(todo);
    },
    // 改ooo
    UpadataIsEdit(id, InputTitle) {
      // console.log(id)
      this.TodoList.forEach((element) => {
        if (element.id === id) {
          // element.isEdit = !element.isEdit
          element.title = InputTitle;
        }
      });
    },
    // 清空选中ooo
    ClearTodos() {
      this.TodoList = this.TodoList.filter((todo) => !todo.done);
    },
    // 全选/不选
    TotalChecked(isAll) {
      this.TodoList.forEach((todo) => (todo.done = isAll));
    },
  },
  // 用数据监视实现浏览器动态缓存数据ooo
  watch: {
    TodoList: {
      deep: true,
      handler(value) {
        localStorage.setItem("todos", JSON.stringify(value));
      }
    }
  },
  mounted() {
    //勾选todo
    this.$bus.$on("handleChange", this.handleChange);
    this.$bus.$on("DeleteTodo", this.DeleteTodo);
    this.$bus.$on("UpadataIsEdit", this.UpadataIsEdit);
  },
  beforeCreate() {
    this.$bus.$off("handleChange");
    this.$bus.$off("DeleteTodo");
    this.$bus.$off("UpadataIsEdit");
  },
};
</script>

<style>
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-edit {
  color: #fff;
  background-color: #77ae83;
  border: 1px solid #66914d;
  margin-right: 10px;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
